<template>
  <div class="chat-container">
    <van-nav-bar
      title="聊天"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      class="chat-nav"
    />
    <div class="message-list" ref="messageList">
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.isSelf ? 'self' : 'other']">
        <div class="avatar">
          <van-image
            round
            width="40"
            height="40"
            :src="msg.avatar"
          />
        </div>
        <div class="content">
          <div class="bubble" :class="msg.type">
            <template v-if="msg.type === 'text'">{{ msg.content }}</template>
            <template v-else-if="msg.type === 'audio'">
              <div class="audio-message" @click="playAudio(msg.content)">
                <van-icon name="volume-o" />
                <span>{{ msg.duration }}s''</span>
              </div>
            </template>
            <template v-else-if="msg.type === 'file'">
              <div class="file-message" @click="downloadFile(msg.content)">
                <van-icon name="description" />
                <span>{{ msg.fileName }}</span>
              </div>
            </template>
            <template v-else-if="msg.type === 'image'">
              <div class="image-message">
                <van-image :src="msg.content" width="200" fit="contain" />
              </div>
            </template>
          </div>
          <div class="message-time">{{ getCurrentTime() }}</div>
        </div>
      </div>
    </div>
    <div class="input-area">
      <div class="input-wrapper">
        <van-button class="voice-btn" size="small" @click="toggleVoiceMode">
          <van-icon :name="isVoiceMode ? 'play-circle-o' : 'volume-o'" size="24" />
        </van-button>
        <van-button
          v-if="isVoiceMode"
          class="voice-record-btn"
          size="large"
          @touchstart="startRecording"
          @touchend="stopRecording"
        >
          按住说话
        </van-button>
        <van-field
          v-else
          v-model="messageText"
          placeholder="请输入消息"
          @keypress.enter="sendTextMessage"
          class="message-input"
        />
        <van-button class="func-btn" size="small">
          <van-icon name="smile-o" size="24" />
        </van-button>
        <van-action-sheet v-model:show="showActionSheet" :actions="actions" cancel-text="取消" close-on-click-action />
        <van-button class="func-btn" size="small" @click="handleActionSelect">
          <van-icon name="plus" size="24" />
        </van-button>
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileUpload"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()
const messageText = ref('')
const messageList = ref(null)
const isRecording = ref(false)
const mediaRecorder = ref(null)
const audioChunks = ref([])

const messages = ref([
  {
    content: '你好！',
    type: 'text',
    isSelf: false,
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  },
  {
    content: '你好！很高兴认识你',
    type: 'text',
    isSelf: true,
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  }
])

const onClickLeft = () => {
  router.back()
}

const sendTextMessage = () => {
  if (!messageText.value.trim()) return
  
  messages.value.push({
    content: messageText.value,
    type: 'text',
    isSelf: true,
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  })
  
  messageText.value = ''
  scrollToBottom()
}

const recordStartTime = ref(null)
const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    mediaRecorder.value = new MediaRecorder(stream)
    audioChunks.value = []
    recordStartTime.value = Date.now()
    
    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.value.push(event.data)
    }
    
    mediaRecorder.value.start()
    isRecording.value = true
  } catch (error) {
    showToast('无法访问麦克风')
    console.error('录音错误:', error)
  }
}

const stopRecording = () => {
  if (!mediaRecorder.value) return
  
  mediaRecorder.value.stop()
  isRecording.value = false
  const duration = Math.round((Date.now() - recordStartTime.value) / 1000)
  
  mediaRecorder.value.onstop = () => {
    const audioBlob = new Blob(audioChunks.value, { type: 'audio/webm' })
    const audioUrl = URL.createObjectURL(audioBlob)
    
    messages.value.push({
      content: audioUrl,
      type: 'audio',
      duration: duration,
      isSelf: true,
      avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
    })
    
    scrollToBottom()
    mediaRecorder.value.stream.getTracks().forEach(track => track.stop())
  }
}

const playAudio = (audioUrl) => {
  const audio = new Audio(audioUrl)
  audio.play()
}

const scrollToBottom = () => {
  setTimeout(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  }, 0)
}

onMounted(() => {
  scrollToBottom()
})

const getCurrentTime = () => {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}

const fileInput = ref(null)

const showActionSheet = ref(false)
const cameraInput = ref(null)
const actions = [
  { 
    name: '拍摄', 
    icon: 'photograph',
    callback: () => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.capture = 'environment'
      input.style.display = 'none'
      input.onchange = (event) => handleFileUpload(event)
      document.body.appendChild(input)
      input.click()
      document.body.removeChild(input)
    }
  },
  { 
    name: '照片', 
    icon: 'photo-o', 
    callback: () => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.style.display = 'none'
      input.onchange = (event) => handleFileUpload(event)
      document.body.appendChild(input)
      input.click()
      document.body.removeChild(input)
    }
  }
]

const handleActionSelect = () => {
  showActionSheet.value = true
}

const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    messages.value.push({
      content: e.target.result,
      type: 'image',
      isSelf: true,
      avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
    })
    scrollToBottom()
  }
  reader.readAsDataURL(file)
  event.target.value = ''
  showActionSheet.value = false
}

const downloadFile = (content) => {
  const link = document.createElement('a')
  link.href = content
  link.download = 'download'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const isVoiceMode = ref(false)

const toggleVoiceMode = () => {
  isVoiceMode.value = !isVoiceMode.value
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.chat-nav {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: #fff;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  padding-bottom: 100px;
}

.input-area {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  padding: 12px;
  background-color: white;
  border-top: 1px solid #eee;
  z-index: 2;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.message {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.message.self {
  flex-direction: row-reverse;
}

.avatar {
  margin: 0 12px;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.self .content {
  align-items: flex-end;
}

.bubble {
  padding: 8px 12px;
  border-radius: 12px;
  word-break: break-word;
  word-wrap: break-word;
  white-space: pre-wrap;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
  margin-bottom: 4px;
  overflow-wrap: break-word;
  hyphens: auto;
  display: inline-block;
  width: fit-content;
}

.bubble::after {
  content: "";
  display: block;
  width: 100%;
  max-width: 20ch;
  word-break: break-all;
}

.bubble.audio {
  min-width: 120px;
}

.self .bubble {
  background-color: #95ec69;
  color: #000;
  border-top-right-radius: 4px;
}

.other .bubble {
  background-color: white;
  border-top-left-radius: 4px;
}

.audio-message {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  min-width: 80px;
  padding: 4px 8px;
}

.audio-message .van-icon {
  font-size: 20px;
}

.record-btn {
  margin-right: 8px;
}

.self .bubble {
  background-color: #07c160;
  color: white;
  border-top-right-radius: 4px;
}

.other .bubble {
  background-color: white;
  border-top-left-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin: 0 4px;
}

.input-area {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  padding: 8px;
  background-color: #f7f7f7;
  border-top: 1px solid #e5e5e5;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f7f7f7;
  padding: 4px;
  border-radius: 4px;
}

.voice-btn,
.func-btn {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
}

.voice-btn .van-icon,
.func-btn .van-icon {
  color: #666;
}

.message-input {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  margin: 0;
  padding: 4px 8px;
}

.message-input :deep(.van-field__control) {
  min-height: 20px;
  font-size: 16px;
}

.message-input {
  background-color: #f5f5f5;
  border-radius: 20px;
  margin-right: 8px;
}

.send-btn {
  border-radius: 20px;
  margin-left: 8px;
}

.file-message {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.file-message .van-icon {
  font-size: 20px;
}

.voice-record-btn {
  flex: 1;
  height: 36px;
  margin: 0 8px;
  border-radius: 18px;
  font-size: 14px;
  background-color: #f5f5f5;
  border: none;
  color: #666;
}

.voice-record-btn:active {
  background-color: #e0e0e0;
}

.image-message {
  max-width: 200px;
  border-radius: 8px;
  overflow: hidden;
}
</style>